package com.alili_tv.system.utils;

import com.alili_tv.system.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 信息合法性校验工具包
 */
@Slf4j
@Component
public class ValidUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 验证手机号合法性
     */
    public static boolean isValidPhone(String phone) {
        if ((phone != null) && (!phone.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        }
        return false;
    }

    /**
     * 验证邮箱合法性
     */
    public static boolean isValidEmail(String email) {
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }
        return false;
    }

    /**
     * 验证码
     * @param account 手机号或邮箱
     * @param code 验证码
     * @param isDelete 验证成功后是否删除缓存的验证码
     * @return
     */
    public boolean validCode(String account, String code, boolean isDelete) {
        if (account == null || code == null) {
            throw new BusinessException("账号或验证码不能为空");
        }
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        String cacheCode = (String) ops.get(account);
        boolean flag = Objects.equals(cacheCode, code);
        if (flag && isDelete) {
            redisTemplate.delete(account);
        }
        return flag;
    }

}